<template>
  <div class="team-contant" v-loading="loading">
    <div style="display: flex" class="w-full h-full">
      <el-card class="left-content" style="width: 200px">
        <div style="align-items: center; padding: 10px">
          <el-tabs
            v-model="activeName"
            class="demo-tabs"
            :class="{ 'opacity-0': arrowRight }"
            @tab-click="handleClick"
          >
            <el-tab-pane label="客服与分组" name="0"></el-tab-pane>
            <el-tab-pane label="角色设置" name="1"></el-tab-pane>
          </el-tabs>
        </div>
        <el-button
          type="primary"
          icon="Plus"
          @click="addGroup"
          v-if="activeName == '0'"
          text
          style="padding-right: 100px"
          >新增分组</el-button
        >
        <el-button
          type="primary"
          icon="Plus"
          @click="addRole"
          v-if="activeName == '1'"
          text
          style="padding-right: 100px"
          >新增角色</el-button
        >

        <el-menu
          style="max-height: 555px; overflow-y: auto"
          class="el-menu-vertical-demo"
          @select="handleSelect"
          v-if="activeName == '1'"
        >
          <el-menu-item
            style="display: inline-flex; justify-content: space-between; width: 100%"
            :index="index"
            v-for="(item, index) in roleList"
            :key="index"
            :class="activeIndex == index ? 'item active-item' : 'item'"
          >
            <span
              >{{ item.name }} <span v-if="item.userCount">({{ item.userCount }})</span></span
            >
            <el-popover
              placement="bottom"
              trigger="hover"
              popper-style="display: inline-flex"
              v-if="index !== 0"
            >
              <template #reference>
                <svg-icon iconClass="icon_more" />
              </template>
              <el-button type="primary" text @click="editRoleByName(item)">编辑</el-button>
              <el-button type="primary" text @click="handleRoleDele(item)">删除</el-button>
            </el-popover>
          </el-menu-item>
        </el-menu>
        <el-menu
          style="max-height: 555px; overflow-y: auto"
          class="el-menu-vertical-demo"
          @select="handleGroupSelect"
          v-if="activeName == '0'"
        >
          <el-menu-item
            :index="index"
            v-for="(item, index) in groupList"
            :key="index"
            style="display: inline-flex; justify-content: space-between; width: 100%"
            :class="activeIndex == index ? 'item active-item' : 'item'"
          >
            <span
              >{{ item.name }} <span v-if="item.userCount">({{ item.userCount }})</span></span
            >

            <el-popover
              placement="bottom"
              trigger="hover"
              popper-style="display: inline-flex"
              v-if="index !== 0"
            >
              <template #reference>
                <svg-icon iconClass="icon_more" />
              </template>
              <el-button type="primary" text @click="handleGroupEdit(item)">编辑</el-button>
              <el-button type="primary" text @click="handleGroupDele(item)">删除</el-button>
            </el-popover>
          </el-menu-item>
        </el-menu>
      </el-card>
      <el-card class="right-content" style="padding: 10px">
        <!-- 客服与分组 -->
        <div v-if="activeName === '0'">
          <el-form
            :inline="true"
            ref="formRef"
            class="login-form"
            :model="form"
            :rules="rules"
            position="top"
          >
            <el-form-item label="账号状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择" clearable style="width: 120px">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="roleCategoryId">
              <el-select
                v-model="form.roleCategoryId"
                placeholder="请选择"
                clearable
                style="width: 120px"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="工号" prop="jobNumber">
              <el-input
                v-model.trim="form.jobNumber"
                v-focus
                placeholder="请输入工号"
                tabindex="1"
                type="text"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="名字" prop="name">
              <el-input
                v-model.trim="form.name"
                v-focus
                placeholder="请输入名字"
                tabindex="1"
                type="text"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">筛选</el-button>
            </el-form-item>
          </el-form>
          <el-row flex justify="space-between" class="w-full">
            <el-button type="primary" @click="addAccount" style="margin: 20px 0 16px 0"
              >添加客服账号</el-button
            >
            <!-- <el-button type="primary" @click="exportMessage">导出 Excel</el-button> -->
          </el-row>
          <el-table :data="tableData">
            <el-table-column label="工号" prop="jobNumber" />
            <el-table-column label="名字" prop="name" />
            <el-table-column label="角色" prop="roleCategoryId">
              <template #default="scope">
                {{
                  scope.row.roleCategoryId
                    ? roleOptions.find((o) => o.value == scope.row.roleCategoryId)?.label
                    : "--"
                }}
              </template>
            </el-table-column>
            <el-table-column label="账号" prop="username" />

            <el-table-column label="权限范围" prop="authority_scope">
              <template #default="scope">
                {{ scope.row.authority_scope == 0 ? "仅自己" : "全部" }}
              </template>
            </el-table-column>
            <el-table-column label="客服名片" prop="nickname" />
            <el-table-column label="服务上限" prop="maxSessionCount" />
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <div style="display: inline-flex; align-items: center">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleEdit(scope)"
                    style="padding: 0 4px; margin-left: 4px"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDelete(scope)"
                    style="padding: 0 4px; margin-left: 4px"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="limit"
            v-model:current-page="form.page"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
        <!-- 角色设置 -->
        <div v-else>
          <div style="color: var(--el-text-color-primary); padding-bottom: 20px">
            角色的权限控制
          </div>
          <el-tree
            :data="all"
            show-checkbox
            node-key="id"
            ref="treeRef"
            :default-checked-keys="defaultCheckedKeys"
            :default-expand-all="true"
            @check="handleCheckChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 添加角色 -->
    <el-dialog v-model="dialogVisible" :title="dialogVisibleTitle" width="500">
      <el-input type="text" placeholder="请输入角色" v-model="roleName"></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddRole"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加分组 -->
    <el-dialog v-model="dialogGroupVisible" :title="dialogGroupVisibleTitle" width="500">
      <el-input type="text" placeholder="请输入分组" v-model="groupName"></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogGroupVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddGroupName"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加客服账号 -->
    <el-dialog :title="dialogCustomTitle" v-model="dialogCustomVisible" width="50%">
      <el-form :model="customForm" :rules="customRules" ref="customFormRef" label-width="120px">
        <el-form-item label="登录邮箱" prop="email">
          <el-input v-model="customForm.email" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="customForm.code" type="text" style="width: calc(100% - 100px)" />
          <el-image v-if="captchaUrl" :src="captchaUrl" @click="changeCode" />
          <div v-else>加载中</div>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="customForm.name" type="text" />
        </el-form-item>
        <el-form-item label="工号" prop="jobNumber">
          <el-input v-model="customForm.jobNumber" type="text" />
        </el-form-item>
        <el-form-item label="服务上限" prop="maxSessionCount">
          <el-input v-model="customForm.maxSessionCount" type="number" />
        </el-form-item>
        <el-form-item label="所属分组" prop="gid">
          <el-select v-model="customForm.gid" placeholder="请选择" clearable style="width: 100%">
            <el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleCategoryId">
          <el-select
            v-model="customForm.roleCategoryId"
            style="width: 100%"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限范围" prop="authority_scope">
          <el-select
            v-model="customForm.authority_scope"
            style="width: 100%"
            placeholder="请选择"
            clearable
          >
            <el-option label="仅自己" :value="0"> </el-option>
            <el-option label="全部" :value="1"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogCustomVisible = false">取消</el-button>
        <el-button type="primary" @click="onCustomSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  onActivated,
  onDeactivated,
  onMounted,
  onUnmounted,
  ref,
  watchEffect,
  getCurrentInstance,
  nextTick,
} from "vue";
import { generateTimestampedRandomNumber } from "@/utils/common.js";

import {
  addRoleByName,
  getAllRole,
  getUserRolesByuserId,
  AddUserGroup,
  getUserGroup,
  getUserListByCondition,
  addUser,
  delteRole,
  editeRole,
  getTreeRoleList,
  getListAllWithRole,
  setRoleCategoryRelation,
  UpdateUserGroup,
  DeleteUserGroup,
  updategroup,
  deletegroup,
} from "@/api/node-admin-api/role";
import { successMessage, warnMessage, errorMessage } from "@/utils/message";

// 角色设置 - 绑定权限
const all = ref([]);
const roles = ref([]);
const rids = ref([]);

const selectedRoleId = ref(null);
const defaultCheckedKeys = ref([]);
const treeRef = ref(null);
const roleTree = ref([]);
const activeRoleId = ref(null);
// 点击列表
const handleSelect = (index) => {
  const id = roleList.value[index].id;
  activeRoleId.value = id;
  fetchAllRoles(id);
  fetchRoles();
};

const handleCheckChange = (data, checked, indeterminate) => {
  if (checked && !rids.value.includes(data.id)) {
    rids.value.push(data.id);
  } else {
    const index = rids.value.findIndex((item) => item.id == data.id);
    if (index !== -1) {
      rids.value.splice(index, 1);
    }
  }
  updateRolePermissions();
};

const findNodeById = (nodes, id) => {
  for (const node of nodes) {
    if (node.id === id) {
      return node;
    }
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
};
// 请求更新角色权限
const updateRolePermissions = () => {
  const params = {
    cid: activeRoleId.value,
    rids: rids.value,
  };
  loading.value = true;
  setRoleCategoryRelation(params)
    .then((res) => {
      if (res.code == 20000) {
        fetchAllRoles(activeRoleId.value);
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 树形结构返回所有权限列表
const fetchRoles = () => {
  loading.value = true;
  getTreeRoleList()
    .then((res) => {
      if (res.code == 20000) {
        all.value = transformData(res.data.roles || []);
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 格式转换为 tree 可用的结构
function transformData(data) {
  function transformNode(node) {
    return {
      id: node.id,
      label: node.name,
      checked: node.selected || false, // 根据原始数据中可能存在的selected属性设置checked
      children: node.children ? node.children.map(transformNode) : [], // 递归转换所有子节点
    };
  }

  return data.map(transformNode);
}

// 根据绑定的权限回显到树桑
function extractCheckedKeys(nodes) {
  let keys = [];
  nodes.forEach((node) => {
    if (node.selected) {
      keys.push(node.id);
    }
    if (node.children && node.children.length > 0) {
      keys = keys.concat(extractCheckedKeys(node.children));
    }
  });
  return keys;
}

//  树形结构返回所有角色和对应的权限
const fetchAllRoles = (id) => {
  loading.value = true;
  getListAllWithRole()
    .then((res) => {
      if (res.code == 20000) {
        const list = res.data.list.filter((o) => o.id == id) || [];
        const keys = extractCheckedKeys(list[0]?.roles || []);
        rids.value = [...keys];
        defaultCheckedKeys.value = [...keys];
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const activeName = ref("0");
const loading = ref(false);
const form = ref({
  status: "0",
  roleCategoryId: "",
  jobNumber: "",
  name: "",
  page: 1,
  limit: 20,
});
const total = ref(0);
const handleClick = ({ props }, event) => {
  const { label, name } = props;
  activeName.value = name;
  if (name == "0") {
    getGroupList();
    getRoleOptions();
  } else {
    getRole({ isFirst: true });
  }
};

onMounted(() => {
  getGroupList({ isfirst: true });
  getRoleOptions();
});

const roleList = ref([]);
const getRole = (val) => {
  const isFirst = val ? val.isFirst : false;
  loading.value = true;
  getAllRole()
    .then((res) => {
      if (res.code == 20000) {
        const list = res.data.result;
        list.unshift({ name: "全部角色", userCount: res.data.result.length });
        roleList.value = list || [];
      } else {
        errorMessage(res.message);
      }

      if (isFirst) {
        handleSelect(1);
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 添加角色
const dialogVisible = ref(false);
const roleName = ref("");
const dialogVisibleTitle = ref("");
const addRole = () => {
  roleName.value = "";
  dialogVisible.value = true;
  dialogVisibleTitle.value = "新增角色";
};

const handleAddRole = () => {
  if (!roleName.value) {
    errorMessage("请输入角色名字！");
    return;
  }
  loading.value = true;
  if (dialogVisibleTitle.value == "新增角色") {
    addRoleByName({ name: roleName.value })
      .then((res) => {
        if (res.code == 20000) {
          successMessage("添加角色成功");
          getRole();
        } else {
          errorMessage(res.message);
        }
      })
      .catch((e) => {
        errorMessage(e.message);
      })
      .finally((res) => {
        dialogVisible.value = false;

        loading.value = false;
      });
  } else {
    handleRoleEdit();
  }
};

// 添加分组
const groupList = ref([]);
const dialogGroupVisible = ref(false);
const dialogGroupVisibleTitle = ref("");
const groupName = ref("");
const addGroup = () => {
  groupName.value = "";
  dialogGroupVisible.value = true;
  dialogGroupVisibleTitle.value = "新增分组";
};
const handleAddGroupName = () => {
  if (!groupName.value) {
    errorMessage("请输入分组名字！");
    return;
  }
  loading.value = true;
  if (dialogGroupVisibleTitle.value == "新增分组") {
    AddUserGroup({ name: groupName.value })
      .then((res) => {
        if (res.code == 20000) {
          successMessage("添加分组成功");
          getGroupList();
        } else {
          errorMessage(res.message);
        }
      })
      .catch((e) => {
        errorMessage(e.message);
      })
      .finally((res) => {
        dialogGroupVisible.value = false;

        loading.value = false;
      });
  } else {
    UpdateUserGroup({ name: groupName.value, id: groupInfoForm.value.id })
      .then((res) => {
        if (res.code == 20000) {
          successMessage("修改分组成功");
          getGroupList();
        } else {
          errorMessage(res.message);
        }
      })
      .catch((e) => {
        errorMessage(e.message);
      })
      .finally((res) => {
        dialogGroupVisible.value = false;
        loading.value = false;
      });
  }
};

const getGroupList = async (val) => {
  const isfirst = val ? val.isfirst : false;
  loading.value = true;
  await getUserGroup()
    .then((res) => {
      if (res.code == 20000) {
        const list = res.data.records;
        list.unshift({ name: "全部分组", userCount: res.data.records.length });
        groupList.value = list || [];
        if (isfirst) {
          handleGroupSelect(1);
        }
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const tableData = ref([]);
const activeIndex = ref(0);
const handleGroupSelect = (index) => {
  if (!index && index !== 0) return;
  activeIndex.value = index;
  const gid = groupList.value[index].id;
  const params = { ...form.value, gid: gid };
  loading.value = true;
  getUserListByCondition(params)
    .then((res) => {
      if (res.code == 20000) {
        tableData.value = res.data.records;
        total.value = res.data.total;
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 账号状态
const statusOptions = ref([
  { label: "未激活", value: "0" },
  { label: "已激活", value: "1" },
]);

// 角色
const roleOptions = ref([]);
const getRoleOptions = async () => {
  loading.value = true;
  await getAllRole()
    .then((res) => {
      if (res.code == 20000) {
        roleOptions.value = res.data.result.map((item) => {
          return { label: item.name, value: item.id };
        });
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 筛选
const search = () => {
  handleGroupSelect(activeIndex.value);
  getRoleOptions();
};

// 导出 Excel
const exportMessage = () => {};

// 添加客服账号
const addAccount = () => {
  changeCode();
  dialogCustomVisible.value = true;
  dialogCustomTitle.value = "新增客服";
  customForm.value = {};
};
// 编辑
const handleEdit = (scope) => {
  changeCode();
  dialogCustomTitle.value = "编辑客服";
  customForm.value = { ...scope.row };
  dialogCustomVisible.value = true;
};
// 删除
const handleDelete = (scope) => {
  loading.value = true;
  deletegroup({ userId: scope.row.userId })
    .then((res) => {
      if (res.code == 20000) {
        handleGroupSelect(activeIndex.value);
        successMessage("删除成功");
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 新增 | 编辑客服账号
const dialogCustomVisible = ref(false);
const dialogCustomTitle = ref("");
const customFormRef = ref(null);

const customForm = ref({
  email: "",
  code: "",
  name: "",
  jobNumber: "",
  maxSessionCount: "99",
  group: "",
  role: "",
  authority_scope: 0,
});

const customRules = {
  email: [
    { required: true, message: "请输入登录邮箱", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  name: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  maxSessionCount: [{ required: true, message: "请输入服务上限", trigger: "blur" }],
  gid: [{ required: true, message: "请选择所属分组", trigger: "change" }],
  roleCategoryId: [{ required: true, message: "请选择角色", trigger: "change" }],
  authority_scope: [{ required: true, message: "请选择权限范围", trigger: "change" }],
};

const idValues = generateTimestampedRandomNumber();
const visitorId = ref(idValues);

const captchaUrl = ref(`http://api.kefu.xurj.top/captcha/image?deviceId=${visitorId.value}`);
const changeCode = () => {
  const temp = new Date().getTime();
  visitorId.value = generateTimestampedRandomNumber();
  captchaUrl.value = `http://api.kefu.xurj.top/captcha/image?deviceId=${visitorId.value}`;
};
const onCustomSubmit = () => {
  customFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      if (dialogCustomTitle.value == "新增客服") {
        const params = {
          ...customForm.value,
          deviceId: visitorId.value,
        };
        addUser(params)
          .then((res) => {
            if (res.code == 20000) {
              handleGroupSelect(activeIndex.value);
              successMessage("保存成功");
            } else {
              errorMessage(res.message);
            }
          })
          .catch((res) => {
            errorMessage(res.message);
          })
          .finally((res) => {
            dialogCustomVisible.value = false;
            loading.value = false;
          });
      } else {
        dialogCustomVisible.value = false;
        loading.value = false;
        const params = {
          userId: customForm.value.userId,
          authority_scope: customForm.value.authority_scope,
          email: customForm.value.email,
          gid: customForm.value.gid,
          jobNumber: customForm.value.jobNumber,
          maxSessionCount: customForm.value.maxSessionCount,
          name: customForm.value.name,
          roleCategoryId: customForm.value.roleCategoryId,
        };
        updategroup(params)
          .then((res) => {
            if (res.code == 20000) {
              handleGroupSelect(activeIndex.value);
              successMessage("修改成功");
            } else {
              errorMessage(res.message);
            }
          })
          .catch((res) => {
            errorMessage(res.message);
          })
          .finally((res) => {
            dialogCustomVisible.value = false;
            loading.value = false;
          });
      }
    }
  });
};

const handleSizeChange = (page) => {
  handleGroupSelect(activeIndex.value);
  search();
};

const handleCurrentChange = (newSize) => {
  handleGroupSelect(activeIndex.value);
  search();
};

const groupInfoForm = ref({ name: "", id: null });
const handleGroupEdit = (item) => {
  groupInfoForm.value = { ...item };
  dialogGroupVisible.value = true;
  dialogGroupVisibleTitle.value = "编辑分组";
  groupName.value = item.name;
};
const handleGroupDele = (item) => {
  DeleteUserGroup({ id: item.id })
    .then((res) => {
      if (res.code == 20000) {
        successMessage("删除分组成功");
        getGroupList();
      } else {
        errorMessage(res.message);
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      dialogGroupVisible.value = false;
      loading.value = false;
    });
};

const detailitemRole = ref({ name: "", id: null });
const editRoleByName = (item) => {
  detailitemRole.value = { ...item };
  roleName.value = item.name;
  dialogVisible.value = true;
  dialogVisibleTitle.value = "编辑角色";
};

const handleRoleEdit = (item) => {
  loading.value = true;
  const params = { ...detailitemRole.value, name: roleName.value };
  editeRole(params)
    .then((res) => {
      if (res.code == 20000) {
        successMessage(`删除角色成功`);
        getRole();
        dialogVisible.value = false;
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};
const handleRoleDele = (item) => {
  loading.value = true;
  delteRole({ id: item.id })
    .then((res) => {
      if (res.code == 20000) {
        successMessage(`删除${item.name}角色成功`);
        getRole();
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};
</script>

<style lang="scss" scoped>
.team-contant {
  padding: 10px;
  height: 100%;
}

:deep(.left-content .el-card__body) {
  padding: 0;
  display: flex;
  flex-direction: column;
}
:deep(.right-content) {
  width: calc(100% - 210px);
  margin-left: 10px;
  padding: 0;
}
.active-item {
  color: var(--el-menu-active-color);
}
</style>
